package com.lenovo.smarttraffic.zm;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.zm.Bean.Item2Api;
import com.lenovo.smarttraffic.zm.Bean.Item2JsonBean;
import com.lenovo.smarttraffic.zm.Bean.SenseBean;
import com.lenovo.smarttraffic.zm.Bean.TempBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/*
 *  有bug   时间不够   回头再写    20/06/04  zm
 * */
public class Item2Activity extends BaseActivity {
    String urlTemp = "http://192.168.1.110:8088/transportservice/action/GetWeather.do";
    // String urlSense = "http://192.168.1.110:8088/transportservice/action/GetAllSense.do";
    private TextView temp;
    private int wendu;
    private ImageView iv_icon;
    private ImageView iv_type0;
    private ImageView iv_type1;
    private ImageView iv_type2;
    private ImageView iv_type3;
    private ImageView iv_type4;
    private ImageView iv_type5;
    private TextView tv_type0;
    private TextView tv_type1;
    private TextView tv_type2;
    private TextView tv_type3;
    private TextView tv_type4;
    private TextView tv_type5;
    private LineChart line;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private TextView tv4;
    private TextView tv5;
    private TextView tv6;
    private TextView tv12;
    private TextView tv22;
    private TextView tv32;
    private TextView tv42;
    private TextView tv52;
    private TextView tv62;
    private String TAG = "item2";
    Handler handler = new Handler();
    private TempBean tempBean;
    private SharedPreferences sharedPreferences;
    private String account;
    private List<Integer> listMin = new ArrayList<>();
    private List<Integer> listMax = new ArrayList<>();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            InitData2();
            handler.postDelayed(r, 3000);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item2);
        sharedPreferences = getSharedPreferences("LoginFlag", Context.MODE_PRIVATE);
        //以防止  未登录情况出现
        if (InitApp.isRegister) {
            account = sharedPreferences.getString("account", "user1");
            Log.e(TAG, "======================================= " + sharedPreferences.getString("account", "user1"));
            //登陆未记住密码
            //  if (account.equals("user1")) {
            account = InitApp.UserName;
            //   }
            Log.e(TAG, "success: 登陆");
        } else {
            account = "user1";
            Log.e(TAG, "success: 未登录");
        }
        initView();
        InitData();
        handler.postDelayed(r, 3000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeCallbacks(r);
        OkHttpUtils1.answer = null;
        Log.e(TAG, "onStop: " + "============");
    }

    protected int getLayout() {
        return R.layout.activity_item2;
    }

    private void initView() {
        initToolBar(findViewById(R.id.toolbar), true, getString(R.string.item2));
        temp = findViewById(R.id.temp);
        iv_icon = findViewById(R.id.iv_icon);
        tv_type0 = findViewById(R.id.type0);
        tv_type1 = findViewById(R.id.type1);
        tv_type2 = findViewById(R.id.type2);
        tv_type3 = findViewById(R.id.type3);
        tv_type4 = findViewById(R.id.type4);
        tv_type5 = findViewById(R.id.type5);
        iv_type0 = findViewById(R.id.iv_type0);
        iv_type1 = findViewById(R.id.iv_type1);
        iv_type2 = findViewById(R.id.iv_type2);
        iv_type3 = findViewById(R.id.iv_type3);
        iv_type4 = findViewById(R.id.iv_type4);
        iv_type5 = findViewById(R.id.iv_type5);
        tv1 = findViewById(R.id.tv1);
        tv2 = findViewById(R.id.tv2);
        tv3 = findViewById(R.id.tv3);
        tv4 = findViewById(R.id.tv4);
        tv5 = findViewById(R.id.tv5);
        tv6 = findViewById(R.id.tv6);
        tv12 = findViewById(R.id.tv12);
        tv22 = findViewById(R.id.tv22);
        tv32 = findViewById(R.id.tv32);
        tv42 = findViewById(R.id.tv42);
        tv52 = findViewById(R.id.tv52);
        tv62 = findViewById(R.id.tv62);
        line = findViewById(R.id.line);
    }

    private void initLine() {
        Log.e(TAG, "initLine:]=============================== " + listMax.get(0) + listMin.get(0));
        //禁止缩放
        line.setScaleEnabled(false);
        //禁止描述
        line.setDescription(null);
        //禁止点击
        line.setEnabled(false);
        // 相当于内边距
        line.setExtraOffsets(150, 0, 150, 0);
        //图例为空
        line.getLegend().setEnabled(false);



        List yV1 = new ArrayList();
        for (int x = 0; x < 6; x++) {
            yV1.add(new Entry(x, listMax.get(x)));
        }

        LineDataSet dataSet1 = new LineDataSet(yV1, "");
        dataSet1.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return (int) entry.getY() + "°";
            }
        });
        dataSet1.setHighlightEnabled(false);
        dataSet1.setColor(Color.YELLOW);
        dataSet1.setDrawCircleHole(false);
        dataSet1.setCircleColor(Color.YELLOW);
        dataSet1.setDrawValues(true);




        List yV2 = new ArrayList();
        for (int x = 0; x < 6; x++) {
            yV2.add(new Entry(x, listMin.get(x)));
        }
        LineDataSet dataSet2 = new LineDataSet(yV2, "");
        dataSet2.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return (int) entry.getY() + "°";
            }
        });
        dataSet2.setHighlightEnabled(false);
        dataSet2.setColor(Color.BLUE);
        dataSet2.setDrawCircleHole(false);
        dataSet2.setCircleColor(Color.BLUE);
        dataSet2.setDrawValues(true);



        //关闭  左右轴
        line.getAxisRight().setEnabled(false);

        YAxis yAxis = line.getAxisLeft();
        yAxis.setAxisMinimum(0);
        yAxis.setLabelCount(5, false);
        yAxis.setDrawAxisLine(false);
        yAxis.setDrawGridLines(false);
        yAxis.setDrawLabels(false);


        //关闭x轴
        XAxis xAxis = line.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawLabels(false);


        List<ILineDataSet> list = new ArrayList<>();
        list.add(dataSet1);
        list.add(dataSet2);
        LineData data = new LineData(list);
        line.setData(data);


    }

    public void InitData() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserName", account);
            OkHttpUtils1.doRequest(urlTemp, jsonObject.toString(), new OkHttpUtils1.OnResLis() {
                @Override
                public void success(String result) {
                    Log.e(TAG, "InitData" + result);
                    Gson gson = new Gson();
                    tempBean = gson.fromJson(result, TempBean.class);

                    tv_type0.setText(tempBean.getROWS_DETAIL().get(0).getType());
                    icon(iv_type0, tempBean.getROWS_DETAIL().get(0).getType());
                    tv_type1.setText(tempBean.getROWS_DETAIL().get(1).getType());
                    icon(iv_type1, tempBean.getROWS_DETAIL().get(1).getType());
                    tv_type2.setText(tempBean.getROWS_DETAIL().get(2).getType());
                    icon(iv_type2, tempBean.getROWS_DETAIL().get(2).getType());
                    tv_type3.setText(tempBean.getROWS_DETAIL().get(3).getType());
                    icon(iv_type3, tempBean.getROWS_DETAIL().get(3).getType());
                    tv_type4.setText(tempBean.getROWS_DETAIL().get(4).getType());
                    icon(iv_type4, tempBean.getROWS_DETAIL().get(4).getType());
                    tv_type5.setText(tempBean.getROWS_DETAIL().get(5).getType());
                    icon(iv_type5, tempBean.getROWS_DETAIL().get(5).getType());
                    wendu = tempBean.getWCurrent();
                    temp.setText(wendu + "度   " + tempBean.getROWS_DETAIL().get(1).getType());
                    icon(iv_icon, tempBean.getROWS_DETAIL().get(1).getType());
                    for (int i = 0; i < tempBean.getROWS_DETAIL().size(); i++) {
                        String temperature = tempBean.getROWS_DETAIL().get(i).getTemperature();
                        String[] split = temperature.split("~");
                        Integer min = Integer.valueOf(split[0]);
                        Integer max = Integer.valueOf(split[1]);
//                        Log.e(TAG, "success: " + min + "==" + max);
                        listMin.add(min);
                        listMax.add(max);
                    }
                    initLine();
                    InitData2();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     *垃圾的okhttp
     * 我永远都爱retrofit
     **/
    public void InitData2() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Item2Api item2Api = retrofit.create(Item2Api.class);
        Call<SenseBean> call = item2Api.getCall(new Item2JsonBean("user1"));
        call.enqueue(new Callback<SenseBean>() {
            @Override
            public void onResponse(Call<SenseBean> call, Response<SenseBean> response) {
                SenseBean senseBean = response.body();
                Log.e(TAG, "onResponse: "+senseBean.get_$Pm25291() );
                chage(senseBean);
            }

            @Override
            public void onFailure(Call<SenseBean> call, Throwable t) {

            }
        });

//        JSONObject jsonObject2 = new JSONObject();
//        try {
//            jsonObject2.put("UserName", account);
//            OkHttpUtils1.doRequest(urlSense, jsonObject2.toString(), new OkHttpUtils1.OnResLis() {
//                @Override
//                public void success(String result) {
//                    Log.e(TAG, "InitData2 " + result);
//                    Gson gson1 = new Gson();
//                    senseBean = gson1.fromJson(result, SenseBean.class);
//                    chage();
//                }
//            });
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

    }


    public void icon(ImageView iv_type, String type) {
        if (type.equals("晴")) {
            iv_type.setImageResource(R.mipmap.sun);
        } else if (type.equals("小雨")) {
            iv_type.setImageResource(R.mipmap.rain);
        } else if (type.equals("阴")) {
            iv_type.setImageResource(R.mipmap.cloudy_);
        }
    }


    public void chage(SenseBean senseBean) {
        tv1.setText(senseBean.getLightIntensity() + "");
        tv2.setText(senseBean.get_$Pm25291() + "");
        tv3.setText(senseBean.getCo2() + "");
        tv4.setText(senseBean.getTemperature() + "");
        tv5.setText(senseBean.getHumidity() + "");
        tv6.setText("适宜");
        tv62.setText("适宜");
        if (senseBean.getLightIntensity() < 1000) {
            tv12.setTextColor(Color.parseColor("#4472c4"));
            tv12.setText("弱");
        } else if (senseBean.getLightIntensity() <= 3000) {
            tv12.setTextColor(Color.parseColor("#00b050"));
            tv12.setText("中等");
        } else if (senseBean.getLightIntensity() > 3000) {
            tv12.setTextColor(Color.parseColor("#ff0000"));
            tv12.setText("强");
        }
        if (senseBean.getHumidity() < 50) {
            tv22.setTextColor(Color.parseColor("#ff0000"));
            tv22.setText("较易发");
        } else if (senseBean.getHumidity() >= 50) {
            tv22.setTextColor(Color.parseColor("#ffff40"));
            tv22.setText("少发");
        }
        if (senseBean.getTemperature() < 12) {
            tv32.setTextColor(Color.parseColor("#3462f4"));
            tv32.setText("冷");
        } else if (senseBean.getTemperature() <= 21) {
            tv32.setTextColor(Color.parseColor("#92d050"));
            tv32.setText("舒适");
        } else if (senseBean.getTemperature() < 35) {
            tv32.setTextColor(Color.parseColor("#44dc68"));
            tv32.setText("温暖");
        } else if (senseBean.getTemperature() > 35) {
            tv32.setTextColor(Color.parseColor("#ff0000"));
            tv32.setText("热");
        }
        if (senseBean.getCo2() < 3000) {
            tv42.setTextColor(Color.parseColor("#44dc68"));
            tv42.setText("适宜");
        } else if (senseBean.getCo2() <= 6000) {
            tv42.setTextColor(Color.parseColor("#ffc000"));
            tv42.setText("中");
        } else if (senseBean.getCo2() > 6000) {
            tv42.setTextColor(Color.parseColor("#8149ac"));
            tv42.setText("较不宜");
        }
        if (senseBean.get_$Pm25291() < 35) {
            tv52.setTextColor(Color.parseColor("#44dc68"));
            tv52.setText("优");
        } else if (senseBean.get_$Pm25291() <= 75) {
            tv52.setTextColor(Color.parseColor("#92d050"));
            tv52.setText("良");
        } else if (senseBean.get_$Pm25291() < 115) {
            tv52.setTextColor(Color.parseColor("#ffff40"));
            tv52.setText("轻度污染");
        } else if (senseBean.get_$Pm25291() < 150) {
            tv52.setTextColor(Color.parseColor("#bf9000"));
            tv52.setText("中度污染");
        } else if (senseBean.get_$Pm25291() > 150) {
            tv52.setTextColor(Color.parseColor("#993300"));
            tv52.setText("重度污染");
        }
    }


}
